<template>
  <div class="video-controls" v-if="showControls">
    <!-- 播放/暂停控制 -->
    <div class="control-btn" @click="togglePlay">
      <pause-circle-filled v-if="isPlaying" />
      <play-circle-filled v-else />
    </div>
    <!-- 进度条 -->
    <div class="progress-container" ref="progressContainer" @click="seek">
      <div
        ref="startBtnRef"
        class="trim-handle start-handle"
        :style="{ left: starBtntLeft }"
        @mousedown="startDrag('start')"
        v-if="duration >= 2"
      >
      </div>
      <div
        ref="endBtnRef"
        class="trim-handle end-handle"
        :style="{ left: endBtnLeft }"
        @mousedown="startDrag('end')"
        v-if="duration >= 2"
      >
      </div>
    </div>
    <div class="time-display">
      <span>  {{ formatTime(startTime) }} / {{ formatTime(endTime) }} </span>
     <span class="ml-5"> 总时长:{{ formatTime(duration) }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import {
  PauseCircleFilled,
  PlayCircleFilled,
} from "@ant-design/icons-vue";

const props = defineProps({
  videoRef: {
    type: Object,
    default: () => {},
  },
  videoDuration: {
    type: Number,
    default: 0,
  },
});
const videoPlayer = ref();
const showControls = ref(true);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const startTime = ref(0);
const endTime = ref(0);
const dragging = ref(null);
const progressContainer = ref(null); // 使用 ref 来引用 progressContainer
let starBtntLeft = ref("0%");
let endBtnLeft = ref("100%");
let startBtnRef = ref()
let endBtnRef = ref()
// 格式化时间显示
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};

// 播放/暂停切换
const togglePlay = () => {
  if (currentTime.value + 1 > endTime.value) {
    return;
  }
  if (videoPlayer.value.paused) {
    videoPlayer.value.play();
    isPlaying.value = true;
  } else {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
};

// 开始拖动
const startDrag = (handle) => {
  dragging.value = handle;
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
};
// 拖动处理
const onDrag = (event) => {
  const rect = progressContainer.value.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const newTime = (offsetX / rect.width) * duration.value;
  if (dragging.value === "start") {
    if (newTime + 1 < endTime.value) {
      startTime.value = Math.max(0, newTime);
      videoPlayer.value.currentTime = startTime.value;
    }
  } else if (dragging.value === "end") {
    if (newTime > startTime.value + 1) {
      endTime.value = Math.min(duration.value, newTime);
    }
  }
};

// 停止拖动
const stopDrag = () => {
  dragging.value = null;
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
  videoPlayer.value.pause();
  isPlaying.value = false;
};
const seek = (e) => {
  let startBtnX = startBtnRef.value.getBoundingClientRect().left;
  let endBtnX = endBtnRef.value.getBoundingClientRect().left;
  let mouseClickX = e.clientX;
  let startDiffX = Math.abs(startBtnX - mouseClickX);
  let endDiffX = Math.abs(endBtnX - mouseClickX);
  if(startDiffX > endDiffX){
      dragging.value = "end"
      onDrag(e,'end')
  }else{
       dragging.value = "start"
       onDrag(e)
  }
 
}
const getCropTime = () => {
  return {
    capture_in: startTime.value.toFixed(4),
    capture_out: endTime.value.toFixed(4),
  }
}
defineExpose({
  getCropTime,
})
// 初始化开始和结束时间
onMounted(() => {
  startTime.value = 0;
  endTime.value = duration.value;
});

watch(
  () => props.videoRef,
  (val) => {
    if (val) {
      videoPlayer.value = val;
      videoPlayer.value.addEventListener("timeupdate", () => {
        currentTime.value = videoPlayer.value.currentTime;
        duration.value = videoPlayer.value.duration;
        endTime.value = endTime.value ? endTime.value : duration.value; // 初始化结束时间为视频总时长
        // 将当前时间赋值给 startTime，但确保 startTime 不超过 endTime
        if (currentTime.value + 1 < endTime.value) {
          startTime.value = currentTime.value;
        } else {
          videoPlayer.value.pause();
          isPlaying.value = false;
        }
        // 如果视频结束，播放结束
        if (videoPlayer.value.currentTime >= videoPlayer.value.duration) {
          isPlaying.value = false;
        }
      });
    }
  },
  { deep: true }
);
// 监听 duration 的变化
watch(duration, (newDuration) => {
  if (newDuration > 0) {
    starBtntLeft.value = `${(startTime.value / newDuration) * 100}%`;
    endBtnLeft.value = `${(endTime.value / newDuration) * 100}%`;
  }
});

// 监听 startTime 和 endTime 的变化
watch([startTime, endTime], ([newStartTime, newEndTime]) => {
  if (duration.value > 0) {
    starBtntLeft.value = `${(newStartTime / duration.value) * 100}%`;
    endBtnLeft.value = `${(newEndTime / duration.value) * 100}%`;
  }
});
watch(
  () => props.videoDuration,
  (newDuration) => {
    duration.value = newDuration;
    endTime.value = newDuration;
  }
);
</script>

<style scoped lang="less">
.video-controls {
  width: 100%;
  height: 50px;
  background: var(--ss-primary-color);
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 15px;
  box-sizing: border-box;
  // z-index: 999;
  // margin-top: 3px;

  .control-btn {
    cursor: pointer;
    color: #fff;
    font-size: 28px;
    padding: 5px;
    transition: opacity 0.3s;

    &:hover {
      opacity: 0.8;
    }
  }

  .progress-container {
    flex: 1;
    position: relative;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
    cursor: pointer;
  }

  .trim-handle {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    color: #00ff00;
    transform: translateX(-50%);
    top: -12px;
    width: 2px;
    height: 30px;
    background: #00ff00;
    &:hover {
      opacity: 0.8;
    }
    cursor: all-scroll;
    &::after {
      content: '';
      position: absolute;
      transform: translateX(-50%);
      width: 4px;
      height: 4px;
      background: #00ff00;
      left: 50%;
      bottom: 0;
    
    }
    &::before {
      content: '';
      position: absolute;
      top: 0;
      transform: translateX(-50%);
      width: 4px;
      height: 4px;
      background: #00ff00;
      left: 50%;
    }
  }
 
  .time-display {
    color: #fff;
    font-size: 12px;
  }

  .volume-control {
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      cursor: pointer;
    }

    .volume-slider {
      width: 80px;
      height: 3px;
      background: rgba(255, 255, 255, 0.3);
      appearance: none;

      &::-webkit-slider-thumb {
        appearance: none;
        width: 10px;
        height: 10px;
        background: #fff;
        border-radius: 50%;
      }
    }
  }
}
</style>
